/*
 * @Author: huhui 
 * @Date: 2018-02-10 10:58:07 
 * @Last Modified by: huhui
 * @Last Modified time: 2018-02-10 16:21:11
 * @Brief: gpio function code
 */


#include "xparameters.h"
#include "xgpio.h"
#include "gpio.h"

#define GPIO_ID XPAR_GPIO_0_DEVICE_ID
#define GPIO_CHANNEL 1



static XGpio Gpio; /* The Instance of the GPIO Driver */

/**
 * @brief set specific gpio pin to specifi value
 * 
 * @param pint 0~32
 * @param value 0 or 1
 */
void gpioSetValue(uint32_t pin, uint8_t value)
{
    uint32_t ioValue = 0;
    ioValue = XGpio_DiscreteRead(&Gpio, GPIO_CHANNEL);
    if (value)
    {
        ioValue |= (1 << pin);
    }
    else
    {
        ioValue &= ~(1 << pin);
    }
    XGpio_DiscreteWrite(&Gpio, GPIO_CHANNEL, ioValue);
}

/**
 * @brief get specific gpio pin value
 * 
 * @param pin 
 * @return uint8_t 
 */
uint8_t gpioGetValue(uint32_t pin)
{
    
    uint32_t ioValue;
    ioValue = XGpio_DiscreteRead(&Gpio, GPIO_CHANNEL);
    if(ioValue&(1<<pin))
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
/**
 * @brief set specific gpio pin direction 
 * 
 * @param pin 0~31
 * @param value 0 : output ,1 : input
 */

void gpioSetDir(uint32_t pin, uint8_t value)
{
    uint32_t dirValue = 0;
    dirValue = XGpio_GetDataDirection(&Gpio, GPIO_CHANNEL);
    if (value)
    {
        dirValue |= (1 << pin);
    }
    else
    {
        dirValue &= ~(1 << pin);
    }
    XGpio_SetDataDirection(&Gpio, GPIO_CHANNEL, dirValue);
}

/**
 * @brief gpio initial 
 * 
 * @param void 
 * @return int 
 */
int gpioInit(void)
{
    int Status;
    /* Initialize the GPIO driver */
    Status = XGpio_Initialize(&Gpio, GPIO_ID);
    if (Status != XST_SUCCESS)
    {
        return XST_FAILURE;
    }
    /*set low 16 bit gpio direction as output */
    XGpio_SetDataDirection(&Gpio, GPIO_CHANNEL, 0x0000000000);
    XGpio_DiscreteWrite(&Gpio, GPIO_CHANNEL, 0x1ffff);
    return XST_SUCCESS;
}
